<template>
  <div class="pictures">
    <el-card class="box-card">
      <template v-slot:header>
        <my-breadcrumb>素材管理</my-breadcrumb>
      </template>

      <div class="top-box">
        <el-radio-group size="medium" v-model="collect" @change="changeCollect">
          <el-radio-button :label="false">全部</el-radio-button>
          <el-radio-button :label="true">收藏</el-radio-button>
        </el-radio-group>
        <el-button
          class="uploadbtn"
          type="success"
          size="medium"
          style="float: right"
          @click="showLoad"
          >上传图片素材</el-button
        >
      </div>

      <el-row :gutter="10">
        <el-col
          v-for="item in images"
          :key="item.id"
          class="img_item"
          :xs="12"
          :sm="8"
          :md="6"
          :lg="4"
          :xl="4"
        >
          <el-image
            style="height: 180px; width: 100%"
            :src="item.url"
            fit="cover"
          >
            <div slot="error" class="image-slot">
              <img
                src="@/assets/error.gif"
                alt=""
                style="width: 150px; height: 100px"
              />
            </div>
          </el-image>
          <div class="option">
            <span  :class="{ star: item.is_collected }" @click="swithCollect(item.id,item.is_collected)" class="el-icon-star-off"></span>
            <span @click="delImage(item.id)" class="el-icon-delete"></span>
          </div>
        </el-col>
      </el-row>

      <el-pagination
        @current-change="handleCurrentChange"
        background
        layout="prev, pager, next"
        :total="total_count"
        :page-size="12"
        :current-page="current_page"
      >
      </el-pagination>
    </el-card>

    <el-dialog
      title="选择图片素材"
      :visible.sync="dialogVisible"
      width="30%"
      :append-to-body="true"
    >
    <!--
      1.action:上传文件的地址，需要完整路径
    原因： 我们之前写完整的路径，是因为axios，设置了baseURL，当你使用axios
    发送请求，会自动拼接，但是，这里不是我们发送的，需要传完整的地址
    2.on-success：成功函数
    3.before-upload：上传前的函数(做一些校验，不通过要求，不让上传，文件大小，文件格式)
    4.headers 配置请求头
    原因：element帮你封装好了上传操作，不走axios，axios请求拦截器拦截不到他的请求，不能帮你带token
    需要手动带
    5.name 配置请求是，图片的name，将来后台才能正确保存接收
    -->
      <el-upload
        class="avatar-uploader"
        :action="$http.defaults.baseURL + '/mp/v1_0/user/images'"
        :show-file-list="false"
        :headers="headers"
        name="image"
        :on-success="handleSuccess"
        :before-upload="beforeUpload">
        <el-image @load="handleLoad" :src="imageUrl" v-if="imageUrl" class="avatar"></el-image>
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import { reqGetPictures, reqSwithCollect, reqDeleteImage } from '@/api/pictures.js'
import { getUser } from '@/utils/storage.js'
export default {
  name: 'Pictures',
  data () {
    return {
      images: [], // 图片列表
      current_page: 1, // 当前页
      total_count: 0,
      per_page: 12,
      collect: false,
      dialogVisible: false,
      imageUrl: '',
      headers: {
        Authorization: `Bearer ${getUser().token}`
      }
    }
  },
  created () {
    this.getImages()
  },
  methods: {
    async getImages () {
      try {
        const res = await reqGetPictures({
          per_page: this.per_page,
          page: this.current_page,
          collect: this.collect
        })
        console.log(res.data)
        this.images = res.data.data.results
        this.total_count = res.data.data.total_count // 总条数
        // console.log(res.data)
      } catch (err) {
        console.log(err)
      }
    },
    // 点击页为当前页
    handleCurrentChange (index) {
      this.current_page = index
      // console.log(this.current_page)
      this.getImages()
    },
    // 点击收藏默认第一页并刷新展示
    changeCollect () {
      this.current_page = 1
      this.getImages()
    },
    // 点击了展示对话框
    showLoad () {
      this.dialogVisible = true
    },
    // 成功执行的函数
    handleSuccess (res, file) {
      // console.log(res.data)
      this.imageUrl = res.data.url
      this.$message.success('上传成功')
      this.getImages()
    },
    // 上传前执行的函数
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleLoad () {
      setTimeout(() => {
        this.dialogVisible = false
        this.imageUrl = null
      }, 2000)
    },
    // 收藏图片
    async swithCollect (id, collect) {
      try {
        // 发送收藏和取消收藏
        await reqSwithCollect(id, !collect)
        this.$message.success('操作成功')
        this.getImages()
      } catch (err) {
        this.$message.success('操作失败')
        console.log(err)
      }
    },
    // 删除图片
    async delImage (id) {
      try {
        await reqDeleteImage(id)
        this.$message.success('删除成功')
        // 如果删除，删除到了当前页最后一张，应该渲染的是上一页
        if (this.images.length === 1 && this.current_page > 1) {
          this.current_page--
        }
        this.getImages()
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-radio-group {
  margin-bottom: 15px;
}
.img_item {
  position: relative;
  box-sizing: border-box;
}
.option {
  position: absolute;
  left: 5px;
  right: 5px;
  bottom: 5px;
  height: 30px;
  line-height: 30px;
  background: rgba(0, 0, 0, 0.7);
  text-align: center;
  color: #fff;
  span {
    margin: 0 30px;
    cursor: pointer;
  }
}
.avatar-uploader {
  text-align: center;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader /deep/ .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-pagination {
  margin-top: 20px;
}
.star {
  color: yellow;
}
// .pictures类, 在模板中能找到, 后面的类, 可以不受scoped的限制, 后面的类, 是可以不在模板中的, 也能生效
// .pictures /deep/ .el-pager li.active {
//   background-color: red;
//   border-radius: 2px;
//   color: #fff;
// }
.pictures {
  /deep/ .el-pager li.active {
    background-color: red;
    border-radius: 2px;
    color: #fff;
  }
}
</style>
